package com.km.app.controller.param;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class ParamContext {
    private String query;
    private String type;
    private Map<String, ParamState> state = new HashMap<>();

    private final static Log log = LogFactory
            .getLog(ParamContext.class);

    /**
     * 状态管理器
     *
     * @param query 查询参数字符串
     */
    public ParamContext(String query) {
        this.query = query;
        if (query == null || query.trim().length() == 0) {
            return;
        }
        String[] var1 = query.split(",");
        if (var1 == null || var1.length == 0) {
            return;
        }
        for (String var2 : var1) {
            if (var2 == null || var2.trim().length() == 0) {
                continue;
            }
            if (var2.indexOf("/") > -1) {
                type = var2;
                return;
            }
        }
    }

    /**
     * 判断是否为图片
     *
     * @param src
     * @return
     */
    private boolean isImage(String src) {
        String contentType = getContentType(src);
        return contentType.equals("image/jpeg") ||
                contentType.equals("image/jpg") ||
                contentType.equals("image/gif") ||
                contentType.equals("image/png") ||
                contentType.equals("image/bmp") ||
                contentType.equals("image/pjpeg") ||
                contentType.equals("image/x-png");
    }

    public String getContentType(String filename) {
        String type = "";
        Path path = Paths.get(filename);
        try {
            type = Files.probeContentType(path);
        } catch (IOException e) {
            log.error(e);
        }
        return type;
    }

    private void write(File file, HttpServletRequest request, HttpServletResponse response) {
        if (file.exists()) {
            byte[] buffer = new byte[4096];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        log.error(e);
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            log.error(e);
                        }
                    }
                }
            }
        }
    }

    /**
     * 添加状态
     *
     * @param state
     */
    public void add(String key, ParamState state) {
        this.state.put(key, state);
    }

    /**
     * 移除状态
     *
     * @param key
     */
    public void remove(String key) {
        this.state.remove(key);
    }

    /**
     * 清空状态
     */
    public void clear() {
        this.state.clear();
    }

    /**
     * 取得查询字符串
     *
     * @return
     */
    public String getQuery() {
        return query;
    }

    /**
     * 设置查询字符串
     *
     * @param query
     */
    public void setQuery(String query) {
        this.query = query;
    }


    /**
     * 执行
     *
     * @return
     */
    public void excute(String src, String fileName, HttpServletRequest request, HttpServletResponse response) {
        ParamState state = this.state.get(this.type);
        File file = null;
        if(type == null){
            type = "";
        }
        if (state != null) {
            file = state.action(this);
        }else{
            file = new File(src);
        }
        if (file != null) {
            if (type.equals("image/download") || type.equals("file/download") || !isImage(src)) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                try {
                    if (request.getHeader("User-Agent") != null && request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                        fileName = URLEncoder.encode(fileName, "UTF-8");
                    } else {
                        fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
                    }
                    response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                response.setContentType(getContentType(src));
            }
            this.write(file, request, response);
        }
    }
}
